package com.own.core.dyn.search;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.Form;


import com.own.core.dyn.list.ListObjectPanel;
import com.own.core.html.form.OwnForm;
import com.own.core.html.form.button.OwnAjaxButton;
import com.own.core.html.form.dropDown.DropDownObj;
import com.own.core.html.form.dropDown.OwnChoiceRenderer;
import com.own.core.html.form.dropDown.OwnDropDown;
import com.own.core.html.form.textField.OwnTextField;
import com.own.core.html.form.textField.TextField;
import com.own.core.html.panel.OwnDynPanel;
import com.own.core.html.panel.OwnPanel;
import com.own.core.model.OwnCompoundPropertyModel;

public class SimpleSearchPanel extends OwnPanel {

	public SimpleSearchPanel(  final ListObjectPanel listPanel) {
		
		super("simpleSearchPanel");
		setParentPanel(listPanel);
		OwnTextField searchTxt = new OwnTextField("textSearch");

		List obj = new ArrayList();
		Field[] fields = getCls().getDeclaredFields();
		for (Field field : fields) {
			Annotation[] annotations = field.getAnnotations();
			OwnDynPanel panel = null;

			for (Annotation ann : annotations) {

				if (ann instanceof TextField) {
					TextField text = (TextField) ann;
					if (text.serachable()) {
						DropDownObj searchObj = new DropDownObj(
								field.getName(), field);
						obj.add(searchObj);
					}// end if search
				}// if text
			}// end for annotation
		}// end for fields
		OwnChoiceRenderer choiceRenderer = new OwnChoiceRenderer("message",
				"field");
		OwnDropDown dropDown = new OwnDropDown("listSearch", obj,
				choiceRenderer);

//		dropDown.setRequired(true);
		OwnAjaxButton searchBtn = new OwnAjaxButton("search") {

			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				DropDownObj dropDownObj = (DropDownObj) form
						.getDefaultModelObject();
				//untill support multi search
				listPanel.clearFilterMap();
				listPanel.addFilter(dropDownObj.getField(),
						dropDownObj.getName());

				target.addComponent(listPanel.getTable());
			}

		};

		OwnAjaxButton clearBtn = new OwnAjaxButton("clear") {

			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

				listPanel.clearFilterMap();

				target.addComponent(listPanel.getTable());
			}

		};

		OwnForm form = new OwnForm("searchForm");
		OwnCompoundPropertyModel model = new OwnCompoundPropertyModel(
				new DropDownObj());
		add(form);

		form.setDefaultModel(model);
		form.add(searchTxt);
		searchTxt.setModel(model.bind("name"));
		form.add(dropDown);
		dropDown.setModel(model.bind("DropDownObj"));

		form.add(searchBtn);
		form.add(clearBtn);

	}
}
